import os
from PySide6.QtWidgets import QDialog, QFileDialog, QMessageBox
from PySide6.QtCore import Signal, QCoreApplication
from ui.storage_ui import Ui_StorageSettingsDialog
from utils.config_manager import ConfigManager
from utils.log_manager import logger


class StorageController(QDialog):
    settings_applied = Signal()             # 用户点击“应用”后发出配置更新信号
    export_data_requested = Signal()       # 用户点击“导出数据”按钮时发出请求信号
    export_image_requested = Signal()       # 用户点击“导出图像”按钮时发出请求信号

    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_StorageSettingsDialog()
        self.ui.setupUi(self)

        self.config = ConfigManager()
        self.settings = self.config.get_storage_config()

        self._init_dropdown_options()  # 初始化下拉选项（插值算法、色图）
        # 让 Designer 里的文本也刷新一遍
        self.ui.retranslateUi(self)
        self._load_to_ui()             # 加载配置值到界面
        self._bind_signals()           # 绑定交互事件

    def _init_dropdown_options(self):
        """初始化下拉选项中的 key-value 内容 (方案1: 代码里使用 self.tr 包裹中文)"""
        
        self.ui.combo_file_format.clear()
        file_formats = [
            (QCoreApplication.translate("StorageController","CSV（表格）"), "csv"),
            (QCoreApplication.translate("StorageController","TXT（纯文本）"), "txt"),
            (QCoreApplication.translate("StorageController","NumPy二进制（.npy）"), "npy"),
            (QCoreApplication.translate("StorageController","NumPy压缩（.npz）"), "npz"),
            (QCoreApplication.translate("StorageController","Excel（.xlsx）"), "xlsx"),
            (QCoreApplication.translate("StorageController","JSON（结构化文本）"), "json"),
            (QCoreApplication.translate("StorageController","HDF5（层次结构）"), "hdf5"),
            (QCoreApplication.translate("StorageController","MAT（Matlab）"), "mat")
        ]
        for label, value in file_formats:
            self.ui.combo_file_format.addItem(label, value)

        self.ui.combo_image_format.clear()
        image_formats = [
            (QCoreApplication.translate("StorageController","PNG（推荐）"), "png"),
            (QCoreApplication.translate("StorageController","JPG"), "jpg"),
            (QCoreApplication.translate("StorageController","TIFF"), "tiff"),
            (QCoreApplication.translate("StorageController","PDF（矢量图）"), "pdf"),
            (QCoreApplication.translate("StorageController","SVG（矢量图）"), "svg"),
            (QCoreApplication.translate("StorageController","WEBP（压缩图）"), "webp")
        ]
        for label, value in image_formats:
            self.ui.combo_image_format.addItem(label, value)

        self.ui.combo_interpolation_algorithm.clear()
        interpolation_options = [
            (QCoreApplication.translate("StorageController","双线性（bilinear）"), "bilinear"),
            (QCoreApplication.translate("StorageController","双三次（bicubic）"), "bicubic"),
            (QCoreApplication.translate("StorageController","不插值（none）"), "none"),
            (QCoreApplication.translate("StorageController","高斯（gaussian）"), "gaussian"),
            (QCoreApplication.translate("StorageController","兰索斯（lanczos）"), "lanczos"),
            (QCoreApplication.translate("StorageController","黑曼窗（kaiser）"), "kaiser"),
            (QCoreApplication.translate("StorageController","汉明窗（hamming）"), "hamming"),
            (QCoreApplication.translate("StorageController","汉宁窗（hanning）"), "hanning"),
            (QCoreApplication.translate("StorageController","贝塞尔（bessel）"), "bessel"),
            (QCoreApplication.translate("StorageController","埃尔米特（hermite）"), "hermite"),
            (QCoreApplication.translate("StorageController","布莱克曼（blackman）"), "blackman"),
            (QCoreApplication.translate("StorageController","米切尔（mitchell）"), "mitchell"),
            (QCoreApplication.translate("StorageController","Catrom插值（catrom）"), "catrom"),
            (QCoreApplication.translate("StorageController","样条16（spline16）"), "spline16"),
            (QCoreApplication.translate("StorageController","样条36（spline36）"), "spline36"),
            (QCoreApplication.translate("StorageController","正弦（sinc）"), "sinc"),
            (QCoreApplication.translate("StorageController","二次（quadric）"), "quadric")
        ]
        for label, value in interpolation_options:
            self.ui.combo_interpolation_algorithm.addItem(label, value)

        self.ui.combo_color_map.clear()
        colormap_options = [
            (QCoreApplication.translate("StorageController","彩虹（jet）"), "jet"),
            (QCoreApplication.translate("StorageController","灰度（gray）"), "gray"),
            (QCoreApplication.translate("StorageController","热度（hot）"), "hot"),
            (QCoreApplication.translate("StorageController","冷暖（coolwarm）"), "coolwarm"),
            (QCoreApplication.translate("StorageController","等离子（plasma）"), "plasma"),
            (QCoreApplication.translate("StorageController","暗紫（magma）"), "magma"),
            (QCoreApplication.translate("StorageController","亮绿（viridis）"), "viridis"),
            (QCoreApplication.translate("StorageController","立体色谱（nipy_spectral）"), "nipy_spectral"),
            (QCoreApplication.translate("StorageController","立体彩虹（rainbow）"), "rainbow"),
            (QCoreApplication.translate("StorageController","金属铜（copper）"), "copper"),
            (QCoreApplication.translate("StorageController","骨架（bone）"), "bone"),
            (QCoreApplication.translate("StorageController","大地（terrain）"), "terrain"),
            (QCoreApplication.translate("StorageController","海洋（ocean）"), "ocean"),
            (QCoreApplication.translate("StorageController","粉红（pink）"), "pink"),
            (QCoreApplication.translate("StorageController","冬季（winter）"), "winter"),
            (QCoreApplication.translate("StorageController","夏季（summer）"), "summer"),
            (QCoreApplication.translate("StorageController","春季（spring）"), "spring"),
            (QCoreApplication.translate("StorageController","秋季（autumn）"), "autumn"),
            (QCoreApplication.translate("StorageController","彩带（spectral）"), "spectral"),
            (QCoreApplication.translate("StorageController","Turbo（turbo）"), "turbo")
        ]
        for label, value in colormap_options:
            self.ui.combo_color_map.addItem(label, value)

    def _load_to_ui(self):
        """将配置内容加载到界面中"""
        self.ui.lineEdit_storage_path.setText(self.settings.get('data_path', './result/data'))
        self.ui.lineEdit_image_path.setText(self.settings.get('image_path', './result/pic'))

        # 恢复数据文件格式（小写值）
        file_format = self.settings.get('file_format', 'csv')
        index = self.ui.combo_file_format.findData(file_format)
        if index != -1:
            self.ui.combo_file_format.setCurrentIndex(index)

        # 恢复图像格式（小写值）
        image_format = self.settings.get('image_format', 'png')
        index = self.ui.combo_image_format.findData(image_format)
        if index != -1:
            self.ui.combo_image_format.setCurrentIndex(index)

        # 恢复插值算法
        interp_value = self.settings.get('interpolation_algorithm', 'bilinear')
        index = self.ui.combo_interpolation_algorithm.findData(interp_value)
        if index != -1:
            self.ui.combo_interpolation_algorithm.setCurrentIndex(index)

        # 恢复色图
        cmap_value = self.settings.get('color_map', 'jet')
        index = self.ui.combo_color_map.findData(cmap_value)
        if index != -1:
            self.ui.combo_color_map.setCurrentIndex(index)

        self.ui.lineEdit_vmin.setText(str(self.settings.get('vmin', -1)))
        self.ui.lineEdit_vmax.setText(str(self.settings.get('vmax', -1)))
        self.ui.spin_refresh_interval.setValue(int(self.settings.get('refresh_interval', 1)))

        logger.log(QCoreApplication.translate("StorageController","📄 已从配置文件加载存储设置"))

    def showEvent(self, event):
        """每次打开窗口都重新加载配置"""
        self.settings = self.config.get_storage_config()
        self._load_to_ui()
        super().showEvent(event)

    def _bind_signals(self):
        """绑定界面事件"""
        self.ui.btn_browse.clicked.connect(self._browse_data_path)
        self.ui.btn_browse_image.clicked.connect(self._browse_image_path)
        self.ui.btn_apply.clicked.connect(self._apply_settings)
        self.ui.btn_cancel.clicked.connect(self.reject)
        self.ui.btn_export_image.clicked.connect(self._export_image)
        self.ui.btn_export_data.clicked.connect(self._export_data)

    def _browse_data_path(self):
        """弹出对话框选择数据路径"""
        path = QFileDialog.getExistingDirectory(self, QCoreApplication.translate("StorageController","选择数据保存路径"))
        if path:
            self.ui.lineEdit_storage_path.setText(path)

    def _browse_image_path(self):
        """弹出对话框选择图像路径"""
        path = QFileDialog.getExistingDirectory(self, QCoreApplication.translate("StorageController","选择图像保存路径"))
        if path:
            self.ui.lineEdit_image_path.setText(path)

    def _apply_settings(self):
        """点击应用按钮后，收集参数保存配置"""
        try:
            vmin = float(self.ui.lineEdit_vmin.text().strip())
        except ValueError:
            vmin = -1
        try:
            vmax = float(self.ui.lineEdit_vmax.text().strip())
        except ValueError:
            vmax = -1

        new_settings = {
            'data_path': self.ui.lineEdit_storage_path.text().strip() or './result/data',
            'image_path': self.ui.lineEdit_image_path.text().strip() or './result/pic',
            'file_format': self.ui.combo_file_format.currentData(),
            'image_format': self.ui.combo_image_format.currentData(),  # ✅ 获取 data 值（如 "pdf"）
            'interpolation_algorithm': self.ui.combo_interpolation_algorithm.currentData(),
            'color_map': self.ui.combo_color_map.currentData(),
            'vmin': vmin,
            'vmax': vmax,
            'refresh_interval': self.ui.spin_refresh_interval.value()
        }

        self.config.set_storage_config(new_settings)
        logger.log(QCoreApplication.translate("StorageController","✅ 存储设置已保存：{new_settings}").format(new_settings=new_settings))
        QMessageBox.information(self, QCoreApplication.translate("StorageController","成功"), QCoreApplication.translate("StorageController","设置已应用"))
        self.settings_applied.emit()
        # self.accept()

    def _export_data(self):
        """点击导出当前数据时触发，由主程序处理"""
        self.export_data_requested.emit()

    def _export_image(self):
        """点击导出当前图像时触发，由主程序处理"""
        self.export_image_requested.emit()